﻿Public Class GraphBuilder

    ' NOTE: This method is invoked from AppWindow.xaml
    Public Shared Function BuildGraphs() As IEnumerable(Of Graph)
        Return New List(Of Graph)( _
            {
                BuildGraph("Simple.xml"),
                BuildGraph("Complex.xml"),
                BuildGraph("VeryCircular.xml"),
                BuildGraph("SimpleCircular.xml"),
                BuildGraph("ComplexCircular.xml"),
                BuildGraph("SuperCircular.xml")
            })
    End Function

    Private Shared Function BuildGraph(ByVal xmlFileName As String) As Graph

        Dim pathStr As String = String.Format("GraphLogic\{0}", xmlFileName)
        Dim xdoc As XDocument = XDocument.Load(pathStr)

        ' Create a graph.
        Dim graphElem = xdoc.Element("graph")
        Dim title As String = graphElem.Attribute("title").Value
        Dim graph = New Graph(title)

        Dim nodeElems As List(Of XElement) = graphElem.Elements("node").ToList()

        ' Create all of the nodes and add them to the graph.
        For Each nodeElem As XElement In nodeElems

            Dim id As String = nodeElem.Attribute("id").Value
            Dim x As Double = CType(nodeElem.Attribute("x"), Double)
            Dim y As Double = CType(nodeElem.Attribute("y"), Double)

            Dim node = New Node(id, x, y)
            graph.Nodes.Add(node)
        Next

        'Associe chaque noeud avec ses dépendants
        For Each node As Node In graph.Nodes

            Dim nodeId As String = node.ID
            Dim nodeElem = (From elem In nodeElems Where elem.Attribute("id").Value = nodeId Select elem).FirstOrDefault
            Dim dependencyElems As IEnumerable(Of XElement) = nodeElem.Elements("dependency")

            For Each dependencyElem As XElement In dependencyElems

                Dim depID As String = dependencyElem.Attribute("id").Value

                If (depID = nodeId) Then _
                    Throw New Exception("A node cannot be its own dependency.  Node ID = " + depID)

                Dim dependency = (From n In graph.Nodes Where n.ID = depID Select n).FirstOrDefault
                'dependency = graph.Nodes.FirstOrDefault(n >= n.ID = depID)
                If (dependency IsNot Nothing) Then node.NodeDependencies.Add(dependency)

            Next
        Next

        ' Tell the graph to inspect itself for circular dependencies.
        'Graph.CheckForCircularDependencies()

        Return graph

    End Function

End Class